#include "musictable.h"
#include "networkcommunicator.h"

MusicTable::MusicTable(QWidget *parent) : QTableView(parent)
{
    model = new QStandardItemModel(0, 4, this);
    model->setHorizontalHeaderItem(0, new QStandardItem("Song"));
    model->setHorizontalHeaderItem(1, new QStandardItem("Artist"));
    model->setHorizontalHeaderItem(2, new QStandardItem("Album"));
    model->setHorizontalHeaderItem(3, new QStandardItem("Youtube Address"));
    setModel(model);

    QHeaderView* view = new QHeaderView(Qt::Horizontal, this);
    view->setHighlightSections(false);
    view->setClickable(true);
    view->setContextMenuPolicy(Qt::CustomContextMenu);
    setHorizontalHeader(view);

    setEditTriggers(QTableView::NoEditTriggers);
    setSelectionBehavior(QTableView::SelectRows);
    setSortingEnabled(true);

    loadMusic();
    setMinimumWidth(350);

    hideColumn(3);

    setContextMenuPolicy(Qt::ActionsContextMenu);
    editAct = new QAction("Edit", this);
    addAction(editAct);

    QObject::connect(this, SIGNAL(playSong(QString)), NetworkCommunicator::instance(), SLOT(findStreamUrl(QString)));
    QObject::connect(NetworkCommunicator::instance(), SIGNAL(newSearchDone(QList<VideoInfo>)), this, SLOT(refresh(QList<VideoInfo>)));
    QObject::connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(songClicked(QModelIndex)));
    QObject::connect(editAct, SIGNAL(triggered()), this, SLOT(editSong()));
}

void MusicTable::loadMusic()
{
    lib.load_file("library.xml");
    for(pugi::xml_node song = lib.child("Song"); song; song = song.next_sibling())
    {
        QList<QStandardItem*> items;
        items.push_back(new QStandardItem(song.attribute("number").as_string()));
        items.push_back(new QStandardItem(song.attribute("artist").as_string()));
        items.push_back(new QStandardItem(song.attribute("album").as_string()));
        items.push_back(new QStandardItem(song.attribute("address").as_string()));
        model->appendRow(items);
    }
}

void MusicTable::add()
{
    NewSongDialog dialog(this);
    if(dialog.exec())
    {
        //Get the new song's properties
        QString number = dialog.numberEdit->text();
        QString artist = dialog.artistEdit->text();
        QString album = dialog.albumEdit->text();
        QString url = dialog.addressEdit->text();
        extractVideoFromUrl(url);

        //Update the table
        QList<QStandardItem*> items;
        items.push_back(new QStandardItem(number));
        items.push_back(new QStandardItem(artist));
        items.push_back(new QStandardItem(album));
        items.push_back(new QStandardItem(url));
        model->appendRow(items);

        //Update the XML file
        pugi::xml_node song = lib.append_child("Song");
        song.append_attribute("address") = url.toStdString().c_str();
        song.append_attribute("number") = number.toStdString().c_str();
        song.append_attribute("artist") = artist.toStdString().c_str();
        song.append_attribute("album") = album.toStdString().c_str();
        lib.save_file("library.xml");

        resizeRowsToContents();
    }
}

void MusicTable::songClicked(QModelIndex Data)
{
    QString url = model->item(Data.row(), 3)->text();
    emit(playSong(url));
}

void MusicTable::editSong()
{
    //Get the song's current properties
    QString number = model->item(currentIndex().row(), 0)->text();
    QString artist = model->item(currentIndex().row(), 1)->text();
    QString album = model->item(currentIndex().row(), 2)->text();
    QString address = model->item(currentIndex().row(), 3)->text();

    EditSongDialog dialog(number, artist, album, this);

    if(dialog.exec())
    {
        pugi::xml_node song = lib.find_child_by_attribute("address",address.toStdString().c_str());
        //Get the edited song properties
        number = dialog.numberEdit->text();
        artist = dialog.artistEdit->text();
        album = dialog.albumEdit->text();
        //Update the table
        model->item(currentIndex().row(), 0)->setText(number);
        model->item(currentIndex().row(), 1)->setText(artist);
        model->item(currentIndex().row(), 2)->setText(album);
        //Update the XML file
        song.attribute("number").set_value(number.toStdString().c_str());
        song.attribute("artist").set_value(artist.toStdString().c_str());
        song.attribute("album").set_value(album.toStdString().c_str());
        lib.save_file("library.xml");
    }
}

void MusicTable::extractVideoFromUrl(QString& url)
{
    url = url.right(url.size()  - url.lastIndexOf("v=")-2);
    url = url.left(url.indexOf("&"));
}

void MusicTable::refresh(QList<VideoInfo> list)
{
    model->removeRows(0,model->rowCount());
    QList<VideoInfo>::Iterator itr = list.begin();
    while(itr != list.end())
    {

        QList<QStandardItem*> items;
        if((*itr).title.indexOf("-") != -1)
            {
            items.push_back(new QStandardItem((*itr).title.right((*itr).title.length() - 2 - (*itr).title.indexOf("-"))));
            items.push_back(new QStandardItem((*itr).title.left((*itr).title.indexOf("-"))));
        }
        else
        {
            items.push_back(new QStandardItem((*itr).title));
            items.push_back(new QStandardItem(""));
        }
        items.push_back(new QStandardItem((*itr).duration));
        items.push_back(new QStandardItem((*itr).id));
        model->appendRow(items);

        itr++;
    }

}

void MusicTable::filter(QString word)
{
    qDebug("Commencing filter procedure");
    if(word.isEmpty())
    {
        for(int i = 0; i < model->rowCount(); i++)
            setRowHidden(i, false);
    }
    else
    {
        //Set ALL rows to hidden
        for(int i = 0; i < model->rowCount(); i++)
            setRowHidden(i, true);
        //Find the matches
        QList<QStandardItem*> matches;
        for(int i = 0; i < model->columnCount(); i++)
            matches += model->findItems(word, Qt::MatchContains, i);
        //Make the matching rows visible
        for(QList<QStandardItem*>::iterator itr = matches.begin(); itr != matches.end(); itr++)
            setRowHidden((*itr)->row(), false);
    }

}
